//
//  QViewUtility.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/1.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QViewUtility.h"
#import "QMainVC.h"
#import "QNewFeatureVC.h"
#import "RTSpinKitView.h"
#import "QNodataView.h"
#import "QDatePickView.h"
#import "QNavigationVC.h"
#import "QShowAlertView.h"
#import "QShowChooseView.h"
#import "QShowWebView.h"
#import "QNoRecordView.h"
#import "QOilTabBarController.h"
#import "QMessageVC.h"
#import "QMySelfVC.h"
#import "QAllOrderMoreVC.h"
#import "QPushModel.h"
#import "QShowPushView.h"

static NSInteger kCustMBProgressTag = 2015;
static NSInteger kMBProgressTag = 2016;
static NSInteger kNODataTag = 2017;
static NSInteger kNONetWorkTag = 2018;
static NSInteger kNoRecordTag = 2019;


@interface QViewUtility()

@end
@implementation QViewUtility

//选择新特性
+ (void)chooseRootViewController:(UIWindow *)window{
    
    NSString *currentVersion = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];
    NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"version"];
    if ([currentVersion isEqualToString:lastVersion]) { // 没有最新的版本号
      //QNavigationVC *nav = [[QNavigationVC alloc] initWithRootViewController:[[QMainVC alloc]init]];
        window.rootViewController = [[QOilTabBarController alloc] init];
    }else{ // 有最新的版本号
        QNewFeatureVC *vc = [[QNewFeatureVC alloc] init];
        window.rootViewController = vc;
        [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:@"version"];
    }
}

+ (NSInteger)getRandomNumber:(int)from to:(int)to{
    
    return (NSInteger)(from + (arc4random()%(to-from + 1)));
}

//显示loading
+ (void)showMBHudToView:(UIView*)view hideBg:(BOOL)hide{
    
    UIView *hud = [view viewWithTag:kMBProgressTag];
    if (hud == nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hud.tag = kMBProgressTag;
        hud.label.text = NSLocalizedString(@"正在加载", @"loading");
        hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.bezelView.color = [UIColor colorWithWhite:0.3 alpha:0.8f];
        if(hide){
         hud.backgroundView.style = MBProgressHUDBackgroundStyleBlur;
        }else{
            hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        }
        hud.backgroundView.color = [UIColor colorWithWhite:0.1f alpha:0.2f];
        hud.removeFromSuperViewOnHide = YES;
        hud.contentColor = [UIColor whiteColor];
        //2  7  10  13 14
        RTSpinKitView *_spinner = [[RTSpinKitView alloc] initWithStyle:13 color:[UIColor whiteColor]];
        hud.customView = _spinner;
        hud.mode = MBProgressHUDModeCustomView;
        [_spinner startAnimating];
    }
}

//隐藏loading
+ (void)hideMBHudToView:(UIView*)view {
    
    [MBProgressHUD hideHUDForView:view animated:YES];
}
//
+ (void)showCustomLoadingToView:(UIView*)view hideBg:(BOOL)hide custTitle:(NSString *)custTitle loadType:(int)type{

    UIView *hud = [view viewWithTag:kCustMBProgressTag];
    if (hud == nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
        hud.tag = kCustMBProgressTag;
        hud.label.text = NSLocalizedString(custTitle, @"loading");
        hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
        hud.bezelView.color = [UIColor colorWithWhite:0.3 alpha:0.8f];
        if(hide){
            hud.backgroundView.style = MBProgressHUDBackgroundStyleBlur;
        }else{
            hud.backgroundView.style = MBProgressHUDBackgroundStyleSolidColor;
        }
        hud.backgroundView.color = [UIColor colorWithWhite:0.1f alpha:0.2f];
        hud.removeFromSuperViewOnHide = YES;
        hud.contentColor = [UIColor whiteColor];
        if(type > 14){
            type = 13;
        }
        RTSpinKitView *_spinner = [[RTSpinKitView alloc] initWithStyle:type color:[UIColor whiteColor]];
        hud.customView = _spinner;
        hud.mode = MBProgressHUDModeCustomView;
        [_spinner startAnimating];
    }
}

//隐藏loading
+ (void)hideCustMBHudToView:(UIView*)view{
    
    [MBProgressHUD hideHUDForView:view animated:YES];
}

//显示数据请求后的message
+ (void)showToastToView:(UIView *)view message:(NSString *)message{

    CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle];
    style.cornerRadius = 5.0;
    style.titleFont = [UIFont systemFontOfSize:16.0];
    style.verticalPadding = 10;
    [view makeToast:message duration:1.5 position:CSToastPositionCenter style:style];
}

//+ (void)showSuccessToastToView:(UIView *)view message:(NSString *)meesage{
//
//    CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle];
//    style.imageSize = CGSizeMake(22, 22);
//    style.cornerRadius = 3.0;
//    style.messageFont = [UIFont systemFontOfSize:16.0];
//    style.messageAlignment = NSTextAlignmentLeft;
//    style.verticalPadding = 12;
//    style.horizontalPadding = 9;
//    [view makeToast:meesage duration:1.5 position:CSToastPositionCenter title:nil image:[UIImage imageNamed:@"true_icon"] style:style completion:nil];
//}
//
//+ (void)showFailToastToView:(UIView *)view message:(NSString *)meesage{
//
//    CSToastStyle *style = [[CSToastStyle alloc] initWithDefaultStyle];
//    style.imageSize = CGSizeMake(22, 22);
//    style.cornerRadius = 3.0;
//    style.messageFont = [UIFont systemFontOfSize:16.0];
//    style.messageAlignment = NSTextAlignmentLeft;
//    style.verticalPadding = 12;
//    style.horizontalPadding = 9;
//    [view makeToast:meesage duration:1.5 position:CSToastPositionCenter title:nil image:[UIImage imageNamed:@"false_icon"] style:style completion:nil];
//}

//miss掉
+ (void)dismissNoDataViewInVC:(UIViewController*)vc {
    QNodataView *view = [vc.view viewWithTag:kNODataTag];
    if (view) {
        [view removeFromSuperview];
    }
}

//没有数据
+ (void)showNoDataViewInView:(UIView*)superView string:(NSString *)string{
    QNodataView *view = [[[NSBundle mainBundle]loadNibNamed:@"QNodataView" owner:nil options:nil] firstObject];
    view.tag = kNODataTag;
    if(string.length == 0){
        view.messageStr.text = @"暂无数据";
    }else{
        view.messageStr.text = string;
    }
    view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [superView addSubview:view];
}

//dismiss掉之前的
+ (void)disMissNoNetWorkInVC:(UIViewController *)vc{
    QNodataView *view = [vc.view viewWithTag:kNONetWorkTag];
    if (view) {
        [view removeFromSuperview];
    }
}

//没有数据（哭泣）
+ (void)showNoRecordViewInView:(UIView *)superView Title:(NSString *)title{
    QNoRecordView * view = [[[NSBundle mainBundle] loadNibNamed:@"QNoRecordView" owner:nil options:nil] firstObject];
    view.tag = kNoRecordTag;
    if (title.length == 0) {
        view.title.text = @"您还没有积分纪录哦~";
    }else{
        view.title.text = title;
    }
    view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-45);
    [superView addSubview:view];
    
}
//移除掉
+ (void)disMissNoRecordInVC:(UIViewController *)vc{
    QNoRecordView * view = [vc.view viewWithTag:kNoRecordTag];
    if (view) {
        [view removeFromSuperview];
    }
}

//没有网络
+ (void)showNoNetWorkInView:(UIView *)superView{
    UIView *view = [[[NSBundle mainBundle]loadNibNamed:@"QNetWorkView" owner:nil options:nil] firstObject];
    view.tag = kNONetWorkTag;
    view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    [superView addSubview:view];
}

//上拉刷新
+ (MJRefreshNormalHeader *)showHeadRefresh:(void(^)())refreshBlock{

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (refreshBlock) {
            refreshBlock();
        }
    }];
    
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"松开刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"加载中..." forState:MJRefreshStateRefreshing];
    return header;
}

//下拉加载
+ (MJRefreshAutoNormalFooter *)showFootRefresh:(void(^)())refreshBlock{
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (refreshBlock) {
            refreshBlock();
        }
    }];
    return footer;
}

//显示弹框
+ (void)showPlayBoxView:(PlayboxViewStyle)style myBlock:(void(^)(NSInteger))block{

    QPlayBoxView *playView = [[QPlayBoxView alloc] initWithStyle:style];
    [playView showPlayBoxView];
    playView.ChooseIndexBlock = ^(NSInteger index){
        if (block) {
            block(index);
        }
    };
}

//给指定人打电话弹框
+ (void)showPhonePlayBoxViewWithName:(NSString *)name Number:(NSString *)number myBlock:(void(^)(NSInteger))block{
    QPlayBoxView *playView = [[QPlayBoxView alloc]initWithName:name Number:number];
    [playView showPlayBoxView];
    playView.ChooseIndexBlock = ^(NSInteger index){
        if (block) {
            block(index);
        }
    };
    
}

//多个订单支付弹框
+ (void)showMorePlayPayViewAmount:(NSString *)amount data:(NSArray *)arr myBlock:(void(^)(NSInteger index))block{
    QShowPayView *view = [[QShowPayView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    view.allMoney = amount;
    view.data = arr;
    [view showPlayBoxView];
    view.block = ^(NSInteger index){
        if(block){
            block(index);
        }
    };
}

//日期控件
+ (void)showDatePickView:(void(^)(NSString *str))block{
    QDatePickView *dateView = [[QDatePickView alloc] init];
    dateView.dateBlock = ^(NSString *str,NSString *time){
        if(block){
            block(str);
        }
    };
    [dateView showPickView];
}

//最新弹框
+ (void)showAlertViewWithImage:(UIImage *)image
                       content:(NSString *)content
                      btnTitle:(NSString *)btnTitle
                          type:(NSInteger)type
                       myBlock:(void(^)())block{
   
    QShowAlertView *alert = [[QShowAlertView alloc] initWithImage:image content:content btnTitle:btnTitle type:type];
    
    alert.block = ^(){
        if(block){
            block();
        }
    };
    [alert showPlayBoxView];
}

+ (void)showAlertChooseViewWithImage:(UIImage *)image
                             content:(NSString *)content
                           leftTitle:(NSString *)leftTitle
                          rightTitle:(NSString *)rightTitle
                                type:(NSInteger)type
                             myBlock:(void(^)(NSInteger tag))block{


    QShowChooseView *alert = [[QShowChooseView alloc] initWithImage:image content:content leftTitle:leftTitle rightTitle:rightTitle type:type];
    alert.block = block;
//    alert.block = ^(NSInteger tag){
//        if(block){
//            block(tag);
//        }
//    };
    [alert showPlayBoxView];
}

//加油提示
+ (void)showAlertWebViewWithUrl:(NSString *)url{
    QShowWebView *view = [[QShowWebView alloc] initWithUrl:url];
    view.block = ^(){
    };
    [view showPlayBoxView];
}




+ (void)setupNavigationBarBackForController:(UIViewController*)controller backSelector:(SEL)backSelector{
    if ([controller isKindOfClass:[QMessageVC class]]) {
        return;
    }
    if ([controller isKindOfClass:[QMySelfVC class]]) {
        return;
    }
    if ([controller isKindOfClass:[QAllOrderMoreVC class]]) {
        return;
    }

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *image = [UIImage imageNamed:@"nav_whiteBack"];
    button.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"nav_grayBack"] forState:UIControlStateHighlighted];
    [button addTarget:controller action:backSelector forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    controller.navigationItem.leftBarButtonItem = leftItem;
    
}

//画线
+ (void)drawSepLineforView:(UIView*)view position:(SepLinePosition)position color:(UIColor*)bgColor
{
    UIView* sepLine = [[UIView alloc]init];
    if (bgColor) {
        sepLine.backgroundColor = bgColor;
    } else {
        sepLine.backgroundColor = [QColorUtility colorWithHexString:@"#e1e1e1"];
    }
    static CGFloat const lineWidth = 0.5f;
    CGSize vSize = view.frame.size;
    if ([view isKindOfClass:[UITableViewCell class]]) {
        vSize = CGSizeMake(kScreenWidth, view.frame.size.height);
    }
    
    switch (position) {
        case SepLinePositionBottom:
            sepLine.frame = CGRectMake(0, vSize.height-lineWidth, vSize.width, lineWidth);
            break;
        case SepLinePositionRight:
            sepLine.frame = CGRectMake(vSize.width-lineWidth, 0, lineWidth, vSize.height);
            break;
        case SepLinePositionLeft:
            sepLine.frame = CGRectMake(0, 0, lineWidth, vSize.height);
            break;
        case SepLinePositionMiddle:
            sepLine.frame = CGRectMake(vSize.width/2, 0, lineWidth, vSize.height);
            break;
        case SepLinePositionTop:
            sepLine.frame = CGRectMake(0, 0, vSize.width, lineWidth);
            break;
            
        default:
            break;
    }
    [view addSubview:sepLine];
}


//创建label
+ (UILabel *)createLabelWithFrame:(CGRect)frame
                             font:(NSInteger)font
                    textAlignment:(NSTextAlignment)textAlignment
                        textColor:(UIColor *)textColor
                             text:(NSString *)text{

    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = textAlignment;
    label.textColor = textColor;
    label.text = text;
    return label;
}

//创建button
+ (UIButton *)createButtonWithFrame:(CGRect)frame
                               font:(NSInteger)font
                              title:(NSString *)title
                         titleColor:(UIColor *)titleColor
                    backgroundColor:(UIColor *)backgroundColor{

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:font];
    button.backgroundColor = backgroundColor;
    return button;
}

+ (void)callPhone{
    
//    NSURL *url=[NSURL URLWithString:@"telprompt://4008916577"];
//    [[UIApplication sharedApplication]openURL:url];
    NSString * phoneNu=[NSString stringWithFormat:@"tel:400-891-6577"];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNu]];

}

+ (void)callPhoneWithNumber:(NSString *)number{
    NSString * phoneNu=[NSString stringWithFormat:@"tel:%@", [NSString stringWithFormat:@"%@",number]];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNu]];
}

//签到
+ (void)showSignBoxViewWithTitle:(NSString *)title{
    QShowSignBoxView * playBox = [[QShowSignBoxView alloc]initWithTitle:title];
    [playBox showPlayBoxView];
}

//推送弹窗
+ (void)showPushBoxViewWithModel:(QPushModel *)model myBlock:(void(^)(NSInteger))block{

    QShowPushView * playBox = [[QShowPushView alloc] initWithModel:model];
    playBox.block = block;
    playBox.model = model;
    [playBox showPlayBoxView];
    
}
//获取当前控制器
+ (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}
#pragma mark --- 余额显示的动画----
+ (void)setNumberTextOfLabel:(UILabel *)label WithAnimationForValueContent:(CGFloat)value
{
    CGFloat lastValue = [label.text floatValue];
    CGFloat delta = value - lastValue;
    if (delta == 0) {
        return;
    }
    
    if (delta > 0) {
        
        CGFloat ratio = value / 30.0;
        
        NSDictionary *userInfo = @{@"label" : label,
                                   @"value" : @(value),
                                   @"ratio" : @(ratio)
                                   };
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(setupLabel:) userInfo:userInfo repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }
}
- (void)setupLabel:(NSTimer *)timer
{
    NSDictionary *userInfo = timer.userInfo;
    UILabel *label = userInfo[@"label"];
    CGFloat value = [userInfo[@"value"] floatValue];
    CGFloat ratio = [userInfo[@"ratio"] floatValue];
    
    static int flag = 1;
    CGFloat lastValue = [label.text floatValue];
    CGFloat randomDelta = (arc4random_uniform(2) + 1) * ratio;
    CGFloat resValue = lastValue + randomDelta;
    
    if ((resValue >= value) || (flag == 50)) {
        label.text = [NSString stringWithFormat:@"¥%.2f", value];
        flag = 1;
        [timer invalidate];
        timer = nil;
        return;
    } else {
        label.text = [NSString stringWithFormat:@"%.2f", resValue];
    }
    flag++;
}
@end
